package com.hutao.manage.controller;

import java.io.File;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.hutao.manage.component.Config;
import com.hutao.manage.component.MyConfig;
import com.hutao.manage.pojo.LeftMenuPojo;
import com.hutao.manage.pojo.MedicalResourceExamination;
import com.hutao.manage.pojo.TreatmentTrace;
import com.hutao.manage.query.MedRecordQuery;
import com.hutao.manage.query.MedTraceQuery;
import com.hutao.manage.query.MedicalSearchQuery;
import com.hutao.manage.service.BaseInfoService;
import com.hutao.manage.service.BasicInfoService;
import com.hutao.manage.service.MedRecordService;
import com.hutao.manage.service.MedicalRecordRetrievalService;
import com.hutao.manage.service.MedicalRecordService;
import com.hutao.manage.service.TreatmentTraceService;
import com.hutao.manage.util.CookieUtils;
import com.hutao.manage.util.DateUtil;
import com.hutao.manage.util.ExceptionUtil;
import com.hutao.manage.util.FileUtil;
import com.hutao.manage.util.JsonUtils;
import com.hutao.manage.util.ListUtil;
import com.hutao.manage.util.PDFUtil;
import com.hutao.manage.util.Result;
import com.hutao.manage.util.StringUtil;
import com.hutao.manage.util.disk.DiskManageUtil;

@RequestMapping("/statis")
@Controller
public class MedStatisController {
	private static final Logger log = LoggerFactory.getLogger(MedStatisController.class);

	@Autowired
	private MedRecordService medRecordService;

	@Autowired
	private MedicalRecordService medicalRecordService;

	@Autowired
	private BasicInfoService basicInfoService;

	@Autowired
	private MyConfig myConfig;

	@Autowired
	private MedicalRecordRetrievalService medicalRecordRetrievalService;

	@Autowired
	private TreatmentTraceService treatmentTraceService;

	@Autowired
	private BaseInfoService baseInfoService;

	@Autowired
	private Config conf;

	@ResponseBody
	@RequestMapping(value = "/showMedrecordImageByAjax", method = RequestMethod.POST)
	public Result showMedrecordImage(String firstGuid) {
		List<Map<String, Object>> hospitalizationNotes = medRecordService.getHospitalizationNoteByFirstGuid(firstGuid);
		Map<String, Object> map = new HashMap<>();
		map.put("hospitalizationNotes", hospitalizationNotes);
		List<Map<String, Object>> scanFiles = medRecordService.getScanFiles(firstGuid);
		map.put("scanFiles", scanFiles);
		map.put("count", scanFiles.size());
		map.put("hospitalizationNoteResourceUrl", conf.getHospitalizationNoteResourceUrl());
		Result result = new Result(true, "查询成功!", map);
		return result;
	}

	@RequestMapping("/queryMedShelveByAjax")
	public String queryMedShelve(MedTraceQuery params, Model model) {
		LeftMenuPojo leftMenu = LeftMenuPojo.GetLeftMenu("query_module");
		String leftMenuJson = JsonUtils.objectToJson(leftMenu);
		List<Map<String, Object>> treatmentTraces = new ArrayList<Map<String, Object>>();
		int totalCount = 0;
		
		if (!isEmpryParam(params)) {
			params.setStatus(7);
			treatmentTraces = treatmentTraceService.selectMedShelveByTraceType(params);
			totalCount = treatmentTraceService.selectMedShelveByTraceTypeCount(params);
		}
		params.setTotalCounts(totalCount);
		model.addAttribute("treatmentTraces", treatmentTraces);
		model.addAttribute("leftMenuJson", leftMenuJson);
		model.addAttribute("medTraceQuery", params);
		model.addAttribute("offices", basicInfoService.getMedicalOfficesByHospitalId(1));
		return "medtrace/medshelve.page";
	}

	@RequestMapping("/showMedTraceQuery")
	public String showMedTraceQuery(MedTraceQuery params, Model model) {
		LeftMenuPojo leftMenu = LeftMenuPojo.GetLeftMenu("trace_module");
		String leftMenuJson = JsonUtils.objectToJson(leftMenu);
		List<Map<String, Object>> treatmentTraces = new ArrayList<Map<String, Object>>();
		System.out.println("--------------------------------" + params.getOnlyId() + "-----------------------");
		int totalCounts = 0;
		if (!params.IsPropertyEmpty()) {
			treatmentTraces = treatmentTraceService.selectTraceByMedTraceQuery(params);
			totalCounts = treatmentTraceService.selectTraceByMedTraceQueryCount(params);
		}
		params.setTotalCounts(totalCounts);
		model.addAttribute("treatmentTraces", treatmentTraces);
		model.addAttribute("leftMenuJson", leftMenuJson);
		model.addAttribute("traceTypes", basicInfoService.getTreatmentTraceTypes());
		model.addAttribute("medTraceQuery", params);
		return "medtrace/medtracequery.page";
	}

	/**
	 * 病案检索
	 * 
	 * @param medicalSearchQuery
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/selectMedicalRecordRetrievaListAjax", method = RequestMethod.GET)
	public Result selectMedicalRecordRetrievaList(MedicalSearchQuery medicalSearchQuery, HttpServletResponse response) {
		response.setHeader("Access-Control-Allow-Origin", "*");
		Result result = null;

		try {
			List<Map<String, Object>> medicalRecordMap = medicalRecordRetrievalService
					.selectMedicalRecordRetrievaList(medicalSearchQuery);
			result = new Result(true, "查询成功!", medicalRecordMap);
		} catch (Exception e) {
			log.error("病案检索查询失败---" + ExceptionUtil.getStackTrace(e));
			e.printStackTrace();
			result = new Result(false, "查询失败!e={}:" + e.getMessage());
		}

		return result;
	}

	@ResponseBody
	@RequestMapping(value = "/medPutOnShelveList", method = RequestMethod.POST)
	public Result medPutOnShelveList(String guids, HttpServletRequest request) {
		Result result = null;
		try {
			String currentUser = CookieUtils.getCookieValue(request, "userName");
			if (StringUtils.isNoneEmpty(guids)) {
				for (String guid : guids.split(",")) {
					String filePath = myConfig.getHospitalVisitJsonPath() + StringUtil.getLocalPath(guid);
					String fileName = guid + ".json";
					
					String diskName = DiskManageUtil.getDiskNameByFileName(conf.getConfigFileStorageAllDisk(), filePath + fileName);
					
					if (StringUtils.isBlank(diskName)) {
						log.error("本地磁盘{}里面没有找到json文件, filePath={}, visitGuid", conf.getConfigFileStorageAllDisk(), 
								filePath + fileName,guid);
					}
					
					String realFilePath = diskName + filePath.trim().substring(1);
					Map<String, Object> jsonMap = FileUtil.readLineFile(realFilePath, fileName);
					
					if (jsonMap != null) {
						Map<String, Object> examMap = (Map<String, Object>) jsonMap.get("examinationReportsInfo");
						
						if (examMap != null) {
							List<Map<String, Object>> examinationRecords = (List<Map<String, Object>>) examMap
									.get("examinationReportsRecords");
							
							if (null != examinationRecords && examinationRecords.size() > 0) {
								List<List<Map<String, Object>>> lists = ListUtil.split(examinationRecords, 2);
								List<String> pdfPathList = new ArrayList<>();
								File tempfile = new File(conf.getExaminationPdfPath() + "temp/");
								if (!tempfile.exists()) {
									tempfile.mkdirs();
								}
								for (int i = 0; i < lists.size(); i++) {
									String guidStr = StringUtil.getId();
									PDFUtil.getPdfByTemplate(lists.get(i), conf.getExaminationPdfPath() + "template.pdf",
											conf.getExaminationPdfPath() + "temp/pdf" + guidStr + ".pdf");
									pdfPathList.add(conf.getExaminationPdfPath() + "temp/pdf" + guidStr + ".pdf");
								}
								
									File file = new File(conf.getUploadResourcePath() + "examination/" + guid + "/");
									if (!file.exists()) {
										file.mkdirs();
									}
									List<String> pdfImageList = PDFUtil.pdf2Image(pdfPathList,
											conf.getUploadResourcePath() + "/examination/" + guid + "/");
									result = medicalRecordService.addMedicalResourceExamination(pdfImageList, currentUser, guid);
									//删除并发产生的数据
									medicalRecordService.deleteMreByGroupId(guid, conf.getUploadResourcePath() + "/examination/" + guid + "/");
								
							} else {
								result = medicalRecordService.addMedicalResourceExamination(new ArrayList<String>(), currentUser, guid);
							}
						}
					}
				}
			}
			
			return new Result(true, "病案发行成功!");
		} catch (Exception e) {
			log.error("病案发行异常  firstGuid = "  + " " + ExceptionUtil.getStackTrace(e));
			return  new Result(false, "病案发行失败!");
		}
	}

	/**
	 * 病案上架
	 * 
	 * @author yimr
	 * @param guid
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/medPutOnShelve", method = RequestMethod.POST)
	public Result medPutOnShelve(String guid, HttpServletRequest request) {
			try {
				Result result = null;
				String filePath = myConfig.getHospitalVisitJsonPath() + StringUtil.getLocalPath(guid);
				String fileName = guid + ".json";
				
				String diskName = DiskManageUtil.getDiskNameByFileName(conf.getConfigFileStorageAllDisk(), filePath + fileName);
				if (StringUtils.isBlank(diskName)) {
					log.error("本地磁盘{}里面没有找到json文件, filePath={}, visitGuid", conf.getConfigFileStorageAllDisk(), 
							filePath + fileName, guid);
				} 
				
				//写入到本地json文件
				String realFilePath = diskName + filePath.trim().substring(1);
				Map<String, Object> jsonMap = FileUtil.readLineFile(realFilePath, fileName);
				
				String currentUser = CookieUtils.getCookieValue(request, "userName");
				if (jsonMap != null) {
					Map<String, Object> examMap = jsonMap.get("examinationReportsInfo")!=null?(Map<String, Object>)jsonMap.get("examinationReportsInfo"):null;
					if (examMap != null) {
						
						List<Map<String, Object>> examinationRecords = (List<Map<String, Object>>) examMap
								.get("examinationReportsRecords");
						
						if (null != examinationRecords && examinationRecords.size() > 0) {
							List<List<Map<String, Object>>> lists = ListUtil.split(examinationRecords, 2);
							List<String> pdfPathList = new ArrayList<>();
							File tempfile = new File(conf.getExaminationPdfPath() + "temp/");
							if (!tempfile.exists()) {
								tempfile.mkdirs();
							}
							
								for (int i = 0; i < lists.size(); i++) {
									String tempPdfGuid = StringUtil.getId();
									//检验报告单生成pdf
									PDFUtil.getPdfByTemplate(lists.get(i), conf.getExaminationPdfPath() + "template.pdf",
											conf.getExaminationPdfPath() + "temp/pdf" + tempPdfGuid + ".pdf");

									pdfPathList.add(conf.getExaminationPdfPath() + "temp/pdf" + tempPdfGuid + ".pdf");
								}
									
									File file = new File(conf.getUploadResourcePath() + "examination/" + guid + "/");
									if (!file.exists()) {
										file.mkdirs();
									}
									List<String> pdfImageList = PDFUtil.pdf2Image(pdfPathList,
											conf.getUploadResourcePath() + "/examination/" + guid + "/");
									result = medicalRecordService.addMedicalResourceExamination(pdfImageList, currentUser, guid);
									//删除并发产生的数据
									medicalRecordService.deleteMreByGroupId(guid, conf.getUploadResourcePath() + "/examination/" + guid + "/");
									
							}else {
								result = medicalRecordService.addMedicalResourceExamination(new ArrayList<String>(), currentUser, guid);
							}
					} 
							
						}
				return new Result(true, "病案发行成功!");
			} catch (Exception e) {
				e.printStackTrace();
				log.error("病案发行异常  firstGuid = " + guid + " " + ExceptionUtil.getStackTrace(e));
				return new Result(true, "病案发行失败!");
			}
	}
	
	/**
	 * 病案上架
	 * 
	 * @author yimr
	 * @param guid
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/medPutOnShelve1", method = RequestMethod.POST)
	public Result medPutOnShelve1(String guid, HttpServletRequest request) {

		String filePath = myConfig.getHospitalVisitJsonPath() + StringUtil.getLocalPath(guid);
		String fileName = guid + ".json";
		Map<String, Object> jsonMap = FileUtil.readLineFile(filePath, fileName);
		if (jsonMap != null) {
			Map<String, Object> examMap = jsonMap.get("examinationReportsInfo")!=null?(Map<String, Object>)jsonMap.get("examinationReportsInfo"):null;
			if (examMap != null) {
				List<Map<String, Object>> examinationRecords = (List<Map<String, Object>>) examMap
						.get("examinationReportsRecords");
				List<List<Map<String, Object>>> lists = ListUtil.split(examinationRecords, 2);
				List<String> pdfPathList = new ArrayList<>();
				File tempfile = new File(conf.getExaminationPdfPath() + "temp/");
				if (!tempfile.exists()) {
					tempfile.mkdirs();
				}
				for (int i = 0; i < lists.size(); i++) {

					PDFUtil.getPdfByTemplate(lists.get(i), conf.getExaminationPdfPath() + "template.pdf",
							conf.getExaminationPdfPath() + "temp/pdf" + i + ".pdf");

					pdfPathList.add(conf.getExaminationPdfPath() + "temp/pdf" + i + ".pdf");
				}
				File file = new File(conf.getUploadResourcePath() + "examination/" + guid + "/");
				if (!file.exists()) {
					file.mkdirs();
				}
				List<String> pdfImageList = PDFUtil.pdf2Image(pdfPathList,
						conf.getUploadResourcePath() + "/examination/" + guid + "/");
				if (CollectionUtils.isNotEmpty(pdfImageList)) {
					MedicalResourceExamination medicalResourceExamination = null;
					for (String pdfImageName : pdfImageList) {
						medicalResourceExamination = new MedicalResourceExamination();
						medicalResourceExamination.setCreateTime(new Date());
						medicalResourceExamination.setFileName(pdfImageName);
						medicalResourceExamination.setFirstGuid(guid);
						medicalResourceExamination.setStatus(1);
						//medicalRecordService.addMedicalResourceExamination(medicalResourceExamination);
					}
				}
			}

		}

		TreatmentTrace treatmentTrace = new TreatmentTrace();
		String currentUser = CookieUtils.getCookieValue(request, "userName");
		treatmentTrace.setUserId(currentUser);
		treatmentTrace.setTraceDate(new Date());
		treatmentTrace.setTraceTypeId(7);
		treatmentTrace.setTreatmentGuid(guid);
		Result result = null;
		try {
			boolean flag = treatmentTraceService.addMedTraceQuery(treatmentTrace);
			if (flag) {
				result = new Result(flag, "病案上架成功");
			} else {
				result = new Result(flag, "病案上架失败");
			}
		} catch (Exception e) {
			log.error("病案上架失败----" + ExceptionUtil.getStackTrace(e));
			result = new Result(false, "病案上架失败");
			e.getMessage();
		}

		return result;
	}

	/**
	 * 病案示踪
	 * 
	 * @author yimr
	 * @param guid
	 * @param request
	 * @return
	 */
	@RequestMapping("/medTrace")
	public String medTrace(MedRecordQuery params, Model model) {
		LeftMenuPojo leftMenu = LeftMenuPojo.GetLeftMenu("trace_module");
		String leftMenuJson = JsonUtils.objectToJson(leftMenu);
		List<Map<String, Object>> hospitalNotes = new ArrayList<Map<String, Object>>();
		int count = 0;
		if (!isEmptyTraceParams(params)) {
			hospitalNotes = medRecordService.getHospitalizationNoteList(params);
			count = medRecordService.getHospitalizationNoteCount(params);
		}
		params.setTotalCounts(count);
		model.addAttribute("hospitalNotes", hospitalNotes);
		model.addAttribute("leftMenuJson", leftMenuJson);
		model.addAttribute("offices", basicInfoService.getMedicalOfficesByHospitalId(1));

		model.addAttribute("medRecordQuery", params);
		return "medtrace/medtrace.page";
	}

	public boolean isEmptyTraceParams(MedRecordQuery params) {
		if (params == null) {
			return true;
		}
		if (StringUtils.isEmpty(params.getName()) && StringUtils.isEmpty(params.getMrId())
				&& StringUtils.isEmpty(params.getOnlyId()) && StringUtils.isEmpty(params.getIdCard())
				&& params.getOutHospitalOfficeId() == null && params.getOutHospitalStartDate() == null
				&& params.getOutHospitalEndDate() == null) {
			return true;
		}
		return false;
	}

	/**
	 * 示踪详情
	 * 
	 * @author yimr
	 * @param guid
	 * @param request
	 * @return
	 */
	@RequestMapping("/medTraceDetail")
	public String medTraceDetail(MedTraceQuery params, Model model) {
		LeftMenuPojo leftMenu = LeftMenuPojo.GetLeftMenu("trace_module");
		String leftMenuJson = JsonUtils.objectToJson(leftMenu);
		List<Map<String, Object>> treatmentTraces = treatmentTraceService.selectTraceByMedTraceQuery(params);

		if (params.IsPropertyEmpty()) {
			List<Map<String, Object>> list = medRecordService.getHospitalizationNoteByFirstGuid(params.getFirstGuid());
			params.setIdCard(String.valueOf(list.get(0).get("id_number")));
			params.setMrId(String.valueOf(list.get(0).get("mr_id")));
			params.setName(String.valueOf(list.get(0).get("name")));
		}

		model.addAttribute("treatmentTraces", treatmentTraces);
		model.addAttribute("leftMenuJson", leftMenuJson);
		model.addAttribute("traceTypes", basicInfoService.getTreatmentTraceTypes());

		model.addAttribute("medTraceQuery", params);
		return "medtrace/medtracedetail.page";
	}

	/* 扫描 */
	@ResponseBody
	@RequestMapping(value = "/getBasicInfoMapAjax", method = RequestMethod.POST)
	public Result getBasicInfoMapAjax(HttpServletResponse response) {
		response.setHeader("Access-Control-Allow-Origin", "*");
		Result result = null;
		try {

			Map<String, List<Map<String, Object>>> map = basicInfoService.getBasicInfos();

			result = new Result(true, "查询成功!", map);
		} catch (Exception e) {
			log.error("扫描查询失败---" + ExceptionUtil.getStackTrace(e));
			e.printStackTrace();
			result = new Result(false, e.getMessage());
		}
		return result;
	}

	@ResponseBody
	@PostMapping("/getChooseOfficeCodeAjax")
	public Result getChooseOfficeCode(String code, HttpServletResponse response) {
		try {
			response.setHeader("Access-Control-Allow-Origin", "*");
			Map<String, Object> map = new HashMap<>();
			List<Map<String, Object>> offices = baseInfoService.getChooseOfficeCode(code);
			map.put("offices", offices);

			return new Result(true, "查询成功!", offices, 200);
		} catch (Exception e) {
			e.printStackTrace();
			return new Result(false, "查询失败!", null, 500);
		}

	}

	/* 扫描 */
	@ResponseBody
	@RequestMapping(value = "/selectUnScanMedicalRecordListAjax", method = RequestMethod.GET)
	public Result selectUnScanMedicalRecordList(MedicalSearchQuery medicalSearchQuery, HttpServletResponse response) {
		response.setHeader("Access-Control-Allow-Origin", "*");
		Result result = null;
		Map<String, Object> map = new HashMap<>();
		try {

			List<Map<String, Object>> list = medicalRecordRetrievalService
					.selectUnScanMedicalRecordList(medicalSearchQuery);
			map.put("list", list);
			map.put("Count", list.size());
			result = new Result(true, "查询成功!", map);
		} catch (Exception e) {
			log.error("扫描查询失败---" + ExceptionUtil.getStackTrace(e));
			e.printStackTrace();
			result = new Result(false, e.getMessage());
		}
		return result;
	}

	/* 扫描 */
	@ResponseBody
	@RequestMapping(value = "/selectScanMedicalRecordListAjax", method = RequestMethod.GET)
	public Result selectScanMedicalRecordList(MedicalSearchQuery medicalSearchQuery, HttpServletResponse response) {
		response.setHeader("Access-Control-Allow-Origin", "*");
		Result result = null;

		try {
			List<Map<String, Object>> list = medicalRecordRetrievalService
					.selectScanMedicalRecordList(medicalSearchQuery);
			result = new Result(true, "查询成功!", list);
		} catch (Exception e) {
			log.error("扫描查询失败---" + ExceptionUtil.getStackTrace(e));
			e.printStackTrace();
			result = new Result(false, e.getMessage());
		}
		return result;
	}

	/**
	 * @author li-mh
	 * 
	 *         在示踪详情中添加病案示踪
	 * 
	 */
	@ResponseBody
	@RequestMapping("/insertMedTrace")
	public Result insertMedTrace(MedTraceQuery medTraceQuery, String traceDate, HttpServletRequest request) {
		TreatmentTrace treatmentTrace = new TreatmentTrace();
		String currentUser = CookieUtils.getCookieValue(request, "userName");
		treatmentTrace.setUserId(currentUser);

		if (medTraceQuery.getFirstGuid() != null) {
			treatmentTrace.setTreatmentGuid(medTraceQuery.getFirstGuid());
		}

		if (medTraceQuery.getTraceStartDate() != null) {
			SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

			try {
				treatmentTrace.setTraceDate(dateFormat.parse(traceDate));
			} catch (ParseException e) {
				e.printStackTrace();
			}
		}

		if (medTraceQuery.getTraceTypeId() != null) {
			treatmentTrace.setTraceTypeId(medTraceQuery.getTraceTypeId());
		}

		Result result = null;

		try {
			boolean flag = treatmentTraceService.addMedTraceQuery(treatmentTrace);

			if (flag) {
				result = new Result(flag, "病案示踪添加成功");
			} else {
				result = new Result(flag, "病案示踪添加失败");
			}
		} catch (Exception e) {
			log.error("病案示踪添加失败----" + ExceptionUtil.getStackTrace(e));
			result = new Result(false, "病案示踪添加失败");
			e.getMessage();
		}

		return result;
	}

	/**
	 * 病案评价分页
	 * 
	 * @param params
	 * @param model
	 * @param response
	 * @return
	 */
	@GetMapping("/qualityEvaluationPageAjax")
	@ResponseBody
	public Result ajaxQualityEvaluationPage(MedRecordQuery params, Model model, HttpServletResponse response) {
		response.setHeader("Access-Control-Allow-Origin", "*");
		log.info("----------进入病案评价分页接口----------------");
		Result result = null;

		try {
			Map<String, Object> resultMap = new HashMap<String, Object>();
			List<Map<String, Object>> hospitalNotes = new ArrayList<Map<String, Object>>();
			int count = 0;
			if (!params.IsPropertyEmpty()) {
				hospitalNotes = medicalRecordRetrievalService.ajaxQualityEvaluationPage(params);
				count = (int) medicalRecordRetrievalService.ajaxQualityEvaluationPageTotalCount(params);
			}

			params.setTotalCounts(count);
			resultMap.put("hospitalNotesJson", hospitalNotes);
			resultMap.put("medRecordQuery", params);

			result = new Result(true, "查询成功!", resultMap);

		} catch (Exception e) {
			e.printStackTrace();
			log.error(ExceptionUtil.getStackTrace(e));
			result = new Result(false, "查询失败!");
		}
		return result;
	}

	/**
	 * 根据科室和出院时间查询出院数量
	 * 
	 * @param medRecordQuery
	 * @param response
	 * @return
	 */
	@PostMapping("/getOutHospitalNumByOfficeAndOutTimeAjax")
	@ResponseBody
	public Result getOutHospitalNumByOfficeAndOutTime(MedRecordQuery medRecordQuery, HttpServletResponse response) {
		response.setHeader("Access-Control-Allow-Origin", "*");
		Result result = null;
		try {
			List<Map<String, Object>> outHospitalNumList = medicalRecordRetrievalService
					.getOutHospitalNumByOfficeAndOutTime(medRecordQuery);
			result = new Result(true, "查询成功!", outHospitalNumList);
		} catch (Exception e) {
			result = new Result(false, "查询失败!");
			e.printStackTrace();
			log.error("根据科室和出院日期查询病人出院数量出现异常:" + e.getMessage());
		}
		return result;
	}

	/**
	 * 病案评价分页
	 * 
	 * @param params
	 * @param model
	 * @param response
	 * @return
	 */
	@GetMapping("/firstQualityEvaluationPageAjax")
	@ResponseBody
	public Result ajaxFirstQualityEvaluationPage(MedRecordQuery params, Model model, HttpServletResponse response) {
		response.setHeader("Access-Control-Allow-Origin", "*");
		log.info("----------进入病案评价分页接口----------------");
		Result result = null;

		try {
			Map<String, Object> resultMap = new HashMap<String, Object>();
			List<Map<String, Object>> hospitalNotes = new ArrayList<Map<String, Object>>();
			int count = 0;
			if (!params.IsPropertyEmpty()) {
				hospitalNotes = medicalRecordRetrievalService.ajaxFirstQualityEvaluationPage(params);
				count = (int) medicalRecordRetrievalService.ajaxFirstQualityEvaluationPageTotalCount(params);
			}

			params.setTotalCounts(count);
			resultMap.put("hospitalNotesJson", hospitalNotes);
			resultMap.put("medRecordQuery", params);

			result = new Result(true, "查询成功!", resultMap);
		} catch (Exception e) {
			e.printStackTrace();
			log.error(ExceptionUtil.getStackTrace(e));
			result = new Result(false, "查询失败!");
		}
		return result;
	}

	/**
	 * 根据firstGuid查询病案信息
	 * 
	 * @param firstGuid
	 * @param response
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/getMedRecordByFirstGuidAjax", method = RequestMethod.POST)
	public Result getMedRecordByFirstGuid(String firstGuid, HttpServletResponse response) {
		response.setHeader("Access-Control-Allow-Origin", "*");
		Result result = null;

		try {
			Map<String, Object> map = medicalRecordRetrievalService.getMedRecordByFirstGuid(firstGuid);
			result = new Result(true, "查询成功!", map);
		} catch (Exception e) {
			log.error("扫描查询失败---" + ExceptionUtil.getStackTrace(e));
			e.printStackTrace();
			result = new Result(false, e.getMessage());
		}
		return result;
	}

	/**
	 * 根据firstGuid查询病案信息
	 * 
	 * @param firstGuid
	 * @param response
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/getMedRecordQualityRateAjax", method = RequestMethod.GET)
	public Result getMedRecordQualityRate(MedRecordQuery medRecordQuery, HttpServletResponse response) {
		response.setHeader("Access-Control-Allow-Origin", "*");
		Result result = null;
		// medRecordQuery.setTreamentTraceTypeId(2);
		try {
			Map<String, Object> map = medicalRecordRetrievalService.getMedRecordQualityRate(medRecordQuery);
			result = new Result(true, "查询成功!", map);
		} catch (Exception e) {
			log.error("扫描查询失败---" + ExceptionUtil.getStackTrace(e));
			e.printStackTrace();
			result = new Result(false, e.getMessage());
		}
		return result;
	}

	/**
	 * 病案上架分页查询
	 * 
	 * @param params
	 * @param model
	 * @return
	 */
	@RequestMapping("/queryMedPutAwayByAjax")
	public String queryMedPutAwayByAjax(MedTraceQuery params, Model model) {
		LeftMenuPojo leftMenu = LeftMenuPojo.GetLeftMenu("query_module");
		String leftMenuJson = JsonUtils.objectToJson(leftMenu);
		List<Map<String, Object>> treatmentTraces = new ArrayList<Map<String, Object>>();
		int totalCount = 0;
		if (!isEmpryParam(params)) {
			params.setStatus(12);
			treatmentTraces = treatmentTraceService.selectMedShelveByTraceType(params);
			totalCount = treatmentTraceService.selectMedShelveByTraceTypeCount(params);
		}
		params.setTotalCounts(totalCount);
		model.addAttribute("treatmentTraces", treatmentTraces);
		model.addAttribute("leftMenuJson", leftMenuJson);
		model.addAttribute("medTraceQuery", params);
		model.addAttribute("offices", basicInfoService.getMedicalOfficesByHospitalId(1));
		return "medtrace/medPublish.page";
	}

	public boolean isEmpryParam(MedTraceQuery params) {
		if (params == null) {
			return true;
		}
		if (params.getVisitNumber() == null && StringUtils.isEmpty(params.getMrId())
				&& StringUtils.isEmpty(params.getOnlyId()) && StringUtils.isEmpty(params.getIdCard())
				&& StringUtils.isEmpty(params.getName()) && params.getOutHospitalOfficeId() == null
				&& params.getOutHospitalStartDate() == null && params.getOutHospitalEndDate() == null) {
			return true;
		}
		return false;
	}

	/**
	 * 病案上架
	 * 
	 * @author yimr
	 * @param guid
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/addPutAway", method = RequestMethod.POST)
	public Result addPutAway(TreatmentTrace treatmentTrace, HttpServletRequest request) {
		// TreatmentTrace treatmentTrace = new TreatmentTrace();
		String currentUser = CookieUtils.getCookieValue(request, "userName");
		treatmentTrace.setUserId(currentUser);
		// treatmentTrace.setTraceDate(new Date());
		treatmentTrace.setTraceTypeId(12);
		Result result = null;
		try {
			boolean flag = treatmentTraceService.addMedTraceQuery(treatmentTrace);
			if (flag) {
				result = new Result(flag, "病案上架成功");
			} else {
				result = new Result(flag, "病案上架失败");
			}
		} catch (Exception e) {
			log.error("病案上架失败----" + ExceptionUtil.getStackTrace(e));
			result = new Result(false, "病案上架失败");
			e.getMessage();
		}

		return result;
	}

	@ResponseBody
	@RequestMapping(value = "/getTreatmentTraceByCodeAndGuid", method = RequestMethod.POST)
	public List<Map<String, Object>> getTreatmentTraceByCodeAndGuid(String guid, HttpServletRequest request) {
		List<Map<String, Object>> list = new ArrayList<>();
		try {
			list = medicalRecordRetrievalService.getTreatmentTraceByCodeAndGuid(12, guid);
		} catch (Exception e) {

			e.getMessage();
		}

		return list;
	}

	@ResponseBody
	@RequestMapping(value = "/updateTreatementTrace", method = RequestMethod.POST)
	public Result updateTreatementTrace(TreatmentTrace treatmentTrace, HttpServletRequest request) {
		String currentUser = CookieUtils.getCookieValue(request, "userName");
		treatmentTrace.setUserId(currentUser);
		treatmentTrace.setTraceTypeId(12);
		Result result = null;
		try {
			treatmentTraceService.updateMedTraceQuery(treatmentTrace);
			result = new Result(true, "上架信息修改成功");
		} catch (Exception e) {
			log.error("病案上架失败----" + ExceptionUtil.getStackTrace(e));
			result = new Result(false, "上架信息修改失败");
			e.getMessage();
		}

		return result;
	}

	/* 扫描 */
	@ResponseBody
	@RequestMapping(value = "/getPrintPageByPrintTypeAjax", method = RequestMethod.GET)
	public Result getPrintPageByPrintType(String printTypeId, HttpServletResponse response) {
		response.setHeader("Access-Control-Allow-Origin", "*");
		Result result = null;
		try {

			List<Integer> printPageList = medicalRecordRetrievalService
					.getPrintPageByPrintType(Integer.valueOf(printTypeId));

			System.out.println(printPageList);
			result = new Result(true, "查询成功!", printPageList);
		} catch (Exception e) {
			log.error("扫描查询失败---" + ExceptionUtil.getStackTrace(e));
			e.printStackTrace();
			result = new Result(false, e.getMessage());
		}
		return result;
	}
	
	@ResponseBody
	@RequestMapping(value = "/getApplyMedCountAjax", method = RequestMethod.GET)
	public Result getApplyMedCountAjax( HttpServletResponse response) {
		response.setHeader("Access-Control-Allow-Origin", "*");
		Result result = null;
		try {

			int count= medicalRecordRetrievalService
					.selectMedApplyCount();

			result = new Result(true, "查询成功!", count);
		} catch (Exception e) {
			log.error("扫描查询失败---" + ExceptionUtil.getStackTrace(e));
			e.printStackTrace();
			result = new Result(false, e.getMessage());
		}
		return result;
	}

}
